<?php
declare (strict_types = 1);

namespace daayu\taskload\service;

use daayu\taskload\TaskLoadConfig;
use daayu\taskload\TaskLoadForm;

/**
 * 计划任务Service层
 */
class TaskPlanService extends BaseService
{
    protected $table = 'zn_task_plan';

    public function list($args = [])
    {
        $page = isset($args['page']) ? intval($args['page']) : 1;
        $rows = isset($args['rows']) ? intval($args['rows']) : 20;
        $field = isset($args['field']) ? trim($args['field']) : 'id,project_id,name,describe,monitor_num,command_type,command,time_rule,log_file,status,create_time,update_time';
        $orderBy = isset($args['order_by']) ? $args['order_by'] : 'id desc';
        $where = [];
        if(isset($args['id'])){
            if(is_array($args['id'])){
                $where[] = ['id', 'in', $args['id']];
            }elseif(intval($args['id']) > 0){
                $where[] = ['id', '=', intval($args['id'])];
            }
        }
        if(isset($args['name']) && !empty($args['name'])){
            $where[] = ['name', 'like', '%' . trim($args['name']) . '%'];
        }
        if(isset($args['command']) && !empty($args['command'])){
            $where[] = ['command', 'like', '%' . trim($args['command']) . '%'];
        }
        if(isset($args['status']) && $args['status'] > -1){
            $where[] = ['status', '=', intval($args['status'])];
        }
        if(isset($args['command_type']) && $args['command_type'] > 0){
            $where[] = ['command_type', '=', intval($args['command_type'])];
        }
        if(isset($args['project_id']) && $args['project_id'] > 0){
            $where[] = ['project_id', '=', intval($args['project_id'])];
        }
        if(isset($args['server_id']) && $args['server_id'] > 0){
            $tmp_rs = (new TaskServerRelateService($this->connection))->list(['server_id'=>$args['server_id'], 'rows'=>999, 'total'=>0, 'field'=>'id,task_id']);
            $tmp_ids = array_column($tmp_rs['rows'], 'task_id');
            if(empty($tmp_ids)) $tmp_ids[] = -1;
            $where[] = ['id', 'in', $tmp_ids];
        }
        $rs = $this->table()->where($where)->page($page, $rows)->field($field)->order($orderBy)->select()->toArray();
        if(!empty($rs)){
            $projects = (new TaskProjectService($this->connection))->listName();
            foreach($rs as $k => &$v){
                $v['time_rules'] = explode(' ', $v['time_rule']);
                if(isset($v['command_type'])){
                    $v['command_type_name'] = $this->command_type_names[$v['command_type']] ?? '';
                }
                if(isset($v['status'])){
                    $v['status_name'] = $this->status_names[$v['status']] ?? '';
                }
                if(isset($v['project_id'])){
                    $v['project_name'] = $projects[$v['project_id']] ?? '';
                }
            }
        }
        $ret['total'] = isset($args['total']) ? $args['total'] : $this->table()->where($where)->count();
        $ret['page'] = $page;
        $ret['rows'] = $rs;
        return $ret;
    }

    public function get($id, $field=null)
    {
        $id = intval($id);
        if($id <= 0){
            $this->error = '参数错误';
            return false;
        }
        $info = $this->table()->where('id', $id)->field($field)->find();
        if(!$info){
            $this->error = '指定的记录不存在';
            return false;
        }
        return $info;
    }

    public function save($data = [])
    {
        $id = 0;
        if(isset($data['id'])){
            $id = intval($data['id']);
            unset($data['id']);
            if(empty($id) || $this->table()->where('id', $id)->find() == null){
                $this->error = '指定的记录不存在';
                return false;
            }
        }
        //验证数据
        if(isset($data['project_id'])){
            $data['project_id'] = intval($data['project_id']);
            if($data['project_id'] <= 0){
                $this->error = '所属项目不能为空';
                return false;
            }
        }
        if(isset($data['name'])){
            $data['name'] = trim($data['name']);
            if(empty($data['name'])){
                $this->error = '任务名称不能为空';
                return false;
            }
        }
        if(isset($data['describe'])){
            $data['describe'] = trim($data['describe']);
        }
        if(isset($data['monitor_num'])){
            $data['monitor_num'] = intval($data['monitor_num']);
        }
        if(isset($data['command_type'])){
            $data['command_type'] = intval($data['command_type']);
            if(!in_array($data['command_type'], [1,2,3,4,5])){
                $this->error = '命令类型不正确，只能为[1,2,3,4,5]';
                return false;
            }
        }
        if(isset($data['command'])){
            $data['command'] = trim($data['command']);
            if($data['command_type'] == 2 && !TaskLoadForm::checkUrl($data['command'])){
                $this->error = 'url格式不正确';
                return false;
            }
            if($data['command_type'] != 2 && !TaskLoadForm::checkCommand($data['command'])){
                $this->error = '命令格式不正确';
                return false;
            }
        }
        if(isset($data['time_rule'])){
            $data['time_rule'] = trim($data['time_rule']);
            if(!TaskLoadForm::checkTimeRule($data['time_rule'])){
                $this->error = '执行频率规则格式不正确';
                return false;
            }
            $data['time_rule'] = str_replace('|', ' ', $data['time_rule']);
        }
        if(isset($data['log_file'])){
            $data['log_file'] = trim($data['log_file']);
            if(!TaskLoadForm::checkLogFile($data['log_file'])){
                $this->error = '日志文件名不正确';
                return false;
            }
        }
        if(isset($data['status'])){
            $data['status'] = intval($data['status']);
            if(!in_array($data['status'], [0,1])){
                $this->error = '状态不正确，只能为[0,1]';
                return false;
            }
        }
        if($id > 0){
            $r = $this->table()->where('id', $id)->update($data);
        }else{
            $id = $this->table()->insertGetId($data);
        }
        return $id;
    }

    public function delete($id){
        $id = intval($id);
        if($id <= 0){
            $this->error = '参数错误';
            return false;
        }
        // 启动事务
        $this->db()->startTrans();
        try {
            $r = $this->table()->where('id', $id)->delete();
            //删除相关
            $r = $this->table(TaskLoadConfig::TABLE_TASK_SERVER_RELATE)->where('task_id', $id)->delete();
            // 提交事务
            $this->db()->commit();
            return $r;
        } catch (\Exception $e) {
            // 回滚事务
            $this->db()->rollback();
            $this->error = $e->getMessage();
            return false;
        }
    }

    public function createDb()
    {
        if(!$this->checkTable()){
            $sql = "CREATE TABLE `".$this->table."`  (
                `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
                `project_id` int(11) DEFAULT '0' COMMENT '项目id',
                `name` varchar(150) NULL DEFAULT '' COMMENT '名字',
                `describe` varchar(1000) NULL DEFAULT '' COMMENT '描述',
                `monitor_num` tinyint(4) NULL DEFAULT 0 COMMENT '监控数量 大于0时为监控任务',
                `command_type` tinyint(4) NULL DEFAULT 1 COMMENT '命令类型 1think 2curl 3bash 4python 5php',
                `command` varchar(255) NULL DEFAULT '' COMMENT '执行命令',
                `time_rule` varchar(50) NULL DEFAULT '' COMMENT '时间规则',
                `log_file` varchar(255) NULL DEFAULT '' COMMENT '日志文件名',
                `status` tinyint(4) NULL DEFAULT 0 COMMENT '状态 0禁用 1正常',
                `create_time` timestamp(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
                `update_time` timestamp(0) NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '更新时间',
                PRIMARY KEY (`id`)
              ) ENGINE = InnoDB COMMENT = '计划任务表' ROW_FORMAT = Dynamic";
            $this->db()->execute($sql);
        }
    }
}
